package controller;

import dao.ArticleDao;
import entity.Article;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;

@WebServlet("/article/update")
public class ArticleUpdateServlet extends HttpServlet {
    ArticleDao articleDao = new ArticleDao();
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String id = request.getParameter("id");
        //跳转编辑页面之前先调用dao获取文章a
        Article a = articleDao.getArticleById(id);
        //将文章添加到附加属性作用域
        request.setAttribute("a",a);
        request.getRequestDispatcher("/editArticle.jsp").forward(request,response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //更新文章内容
        String id = request.getParameter("id");
        String title = request.getParameter("title");
        String summary = request.getParameter("summary");
        String content = request.getParameter("content");

        //调用dao层代码进行更新操作
        int total = articleDao.updateArticleById(id,title,summary,content);
        if (total>0){
            response.sendRedirect("/main");
        }else {
            request.getRequestDispatcher("/error.jsp").forward(request,response);
        }
    }
}
